<template>
  <div class="page-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="title">货币管理</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增货币
          </el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :inline="true" class="search-form">
        <el-form-item label="货币名称">
          <el-input v-model="searchForm.name" placeholder="请输入货币名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table :data="tableData" border stripe>
        <el-table-column prop="id" label="编号" width="80" />
        <el-table-column prop="code" label="货币代码" width="120" />
        <el-table-column prop="name" label="货币名称" width="150" />
        <el-table-column prop="symbol" label="符号" width="100" />
        <el-table-column prop="exchangeRate" label="汇率" width="120">
          <template #default="{ row }">
            {{ row.exchangeRate.toFixed(4) }}
          </template>
        </el-table-column>
        <el-table-column prop="isBase" label="本位币" width="100">
          <template #default="{ row }">
            <el-tag :type="row.isBase ? 'success' : 'info'">
              {{ row.isBase ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="150" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="danger" @click="handleDelete(row)" :disabled="row.isBase">删除</el-button>
            <el-button 
              link 
              :type="row.status === 1 ? 'warning' : 'success'" 
              @click="handleToggleStatus(row)"
            >
              {{ row.status === 1 ? '停用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSearch"
        @current-change="handleSearch"
      />
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle"
      width="600px"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="货币代码" prop="code">
          <el-input v-model="form.code" placeholder="如：CNY、USD" />
        </el-form-item>
        <el-form-item label="货币名称" prop="name">
          <el-input v-model="form.name" placeholder="如：人民币、美元" />
        </el-form-item>
        <el-form-item label="符号" prop="symbol">
          <el-input v-model="form.symbol" placeholder="如：¥、$" />
        </el-form-item>
        <el-form-item label="汇率" prop="exchangeRate">
          <el-input-number 
            v-model="form.exchangeRate" 
            :min="0" 
            :precision="4" 
            :step="0.01" 
            :disabled="form.isBase"
          />
          <span class="form-tip">{{ form.isBase ? '本位币汇率固定为1' : '相对于本位币的汇率' }}</span>
        </el-form-item>
        <el-form-item label="本位币" prop="isBase">
          <el-switch v-model="form.isBase" />
          <span class="form-tip">系统只能有一个本位币，汇率为1.0000</span>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="form.remark" 
            type="textarea" 
            :rows="3"
            placeholder="请输入备注信息" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

// 搜索表单
const searchForm = reactive({
  name: ''
})

// 表格数据
const tableData = ref([
  { id: 1, code: 'CNY', name: '人民币', symbol: '¥', exchangeRate: 1.0000, isBase: true, status: 1, remark: '本位币' },
  { id: 2, code: 'USD', name: '美元', symbol: '$', exchangeRate: 0.1379, isBase: false, status: 1, remark: '美国货币' },
  { id: 3, code: 'EUR', name: '欧元', symbol: '€', exchangeRate: 0.1271, isBase: false, status: 1, remark: '欧盟货币' },
  { id: 4, code: 'GBP', name: '英镑', symbol: '£', exchangeRate: 0.1090, isBase: false, status: 1, remark: '英国货币' },
  { id: 5, code: 'JPY', name: '日元', symbol: '¥', exchangeRate: 20.1234, isBase: false, status: 1, remark: '日本货币' },
  { id: 6, code: 'HKD', name: '港币', symbol: 'HK$', exchangeRate: 1.0789, isBase: false, status: 1, remark: '香港货币' }
])

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 6
})

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('新增货币')
const formRef = ref(null)

// 表单数据
const form = reactive({
  id: null,
  code: '',
  name: '',
  symbol: '',
  exchangeRate: 1.0000,
  isBase: false,
  status: 1,
  remark: ''
})

// 表单验证规则
const rules = {
  code: [
    { required: true, message: '请输入货币代码', trigger: 'blur' },
    { min: 3, max: 3, message: '货币代码必须是3个字符', trigger: 'blur' },
    { pattern: /^[A-Z]{3}$/, message: '货币代码必须是3个大写字母', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入货币名称', trigger: 'blur' },
    { min: 2, max: 20, message: '货币名称长度在2-20个字符', trigger: 'blur' }
  ],
  symbol: [
    { required: true, message: '请输入货币符号', trigger: 'blur' }
  ],
  exchangeRate: [
    { required: true, message: '请输入汇率', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value <= 0) {
          callback(new Error('汇率必须大于0'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ]
}

// 搜索
const handleSearch = () => {
  console.log('搜索:', searchForm)
  ElMessage.success('查询成功')
}

// 重置
const handleReset = () => {
  searchForm.name = ''
  handleSearch()
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增货币'
  Object.assign(form, {
    id: null,
    code: '',
    name: '',
    symbol: '',
    exchangeRate: 1.0000,
    isBase: false,
    status: 1,
    remark: ''
  })
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑货币'
  Object.assign(form, { ...row })
  dialogVisible.value = true
}

// 删除
const handleDelete = (row) => {
  if (row.isBase) {
    ElMessage.warning('本位币不能删除')
    return
  }
  ElMessageBox.confirm(`确定要删除货币 "${row.name}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    console.log('删除:', row.id)
    ElMessage.success('删除成功')
  })
}

// 切换状态
const handleToggleStatus = (row) => {
  const status = row.status === 1 ? 0 : 1
  const text = status === 1 ? '启用' : '停用'
  ElMessageBox.confirm(`确定要${text}货币 "${row.name}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    row.status = status
    ElMessage.success(`${text}成功`)
  })
}

// 监听本位币变化
watch(() => form.isBase, (newVal) => {
  if (newVal) {
    // 设为本位币时，汇率自动设为1
    form.exchangeRate = 1.0000
  }
})

// 监听货币代码变化，自动转为大写
watch(() => form.code, (newVal) => {
  if (newVal) {
    form.code = newVal.toUpperCase()
  }
})

// 提交表单
const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      // 检查本位币唯一性
      if (form.isBase) {
        const existingBase = tableData.value.find(item => item.isBase && item.id !== form.id)
        if (existingBase) {
          ElMessageBox.confirm(
            `系统已存在本位币 "${existingBase.name}"，确定要将 "${form.name}" 设为新的本位币吗？这将取消原本位币的设置。`,
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
          ).then(() => {
            // 取消原本位币
            existingBase.isBase = false
            saveForm()
          }).catch(() => {
            form.isBase = false
          })
          return
        }
      }
      
      // 检查货币代码唯一性
      const existingCode = tableData.value.find(item => item.code === form.code && item.id !== form.id)
      if (existingCode) {
        ElMessage.error(`货币代码 "${form.code}" 已存在，请使用其他代码`)
        return
      }
      
      saveForm()
    }
  })
}

// 保存表单
const saveForm = () => {
  console.log('提交:', form)
  ElMessage.success(form.id ? '修改成功' : '新增成功')
  dialogVisible.value = false
  handleSearch()
}
</script>

<style scoped>
.page-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.search-form {
  margin-bottom: 20px;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}

.form-tip {
  margin-left: 10px;
  color: #999;
  font-size: 12px;
}
</style>

